#include "stm32f10x.h"                  // Device header
#include <stdio.h>
#include "Car.h"
#include "Serial.h"
#include "PID.h"
#include "Delay.h"
#include "main.h"

uint8_t Serial_RxFlag=1;
uint8_t Speed = 65;
uint8_t Serial_RxData;

void Serial_Init(void)
{
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART3,ENABLE);
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB,ENABLE);
	
	GPIO_InitTypeDef GPIO_InitStructure;				//瀹氫箟缁撴瀯浣撳彉閲?
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;		//澶嶇敤鎺ㄦ尳杈撳嚭
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_Init(GPIOB,&GPIO_InitStructure);
	
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;		//涓婃媺杈撳叆
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_11;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_Init(GPIOB,&GPIO_InitStructure);
	
	USART_InitTypeDef USART_InitStruture;
	USART_InitStruture.USART_BaudRate = 9600;	
	USART_InitStruture.USART_HardwareFlowControl = USART_HardwareFlowControl_None;	//纭欢娴佹帶
	USART_InitStruture.USART_Mode = USART_Mode_Tx | USART_Mode_Rx;
	USART_InitStruture.USART_Parity = USART_Parity_No;						//鏃犳牎楠屼綅
	USART_InitStruture.USART_StopBits = USART_StopBits_1;					//鍋滄浣?
	USART_InitStruture.USART_WordLength = USART_WordLength_8b;				// 8浣嶅瓧闀?
	USART_Init(USART3,&USART_InitStruture);
	
	USART_ITConfig(USART3, USART_IT_RXNE, ENABLE);
	
	NVIC_PriorityGroupConfig(NVIC_PriorityGroup_3);
	
	NVIC_InitTypeDef NVIC_InitStructure;
	NVIC_InitStructure.NVIC_IRQChannel = USART3_IRQn;
	NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
	NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 3;
	NVIC_InitStructure.NVIC_IRQChannelSubPriority = 3;
	NVIC_Init(&NVIC_InitStructure);
	
	USART_Cmd(USART3,ENABLE);
		
}

void USART3_IRQHandler(void)
{
	if (USART_GetITStatus(USART3, USART_IT_RXNE) == SET)
	{
		Serial_RxData = USART_ReceiveData(USART3);
		if(Speed<=100)
		{
			switch(Serial_RxData)
			{
				case 0X01: Car_Go(Speed);break;
				case 0X02: Car_Back(Speed);break;
				case 0X03: Car_Left(Speed);break;
				case 0X04: Car_Right(Speed);break;
				case 0X00: Car_Stop(0);break;
				case 0X10: Speed -= 2; break;
				case 0X20: Speed = 65; break;
				case 0X30: Speed += 2;break;
				case 0X40: Serial_RxFlag = 0;break;
				case 0X50: Serial_RxFlag = 1;break;
			}
		}
		else
			Speed = 65;								
		USART_ClearITPendingBit(USART3, USART_IT_RXNE);
	}
}
